package com.evil.log.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.evil.common.core.util.RedisUtil;
import com.evil.common.core.util.StreamUtil;
import com.evil.common.log.util.LogRedisKeyUtil;
import com.evil.log.api.RemoteOperationLogService;
import com.evil.log.mapper.OperationLogMapper;
import com.evil.log.pojo.entiy.OperationLog;
import com.evil.log.service.OperationLogService;
import com.evil.log.util.LogUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 操作日志表
 *
 * @author liyang
 * @date 2022-08-08 00:00
 */
@Slf4j
@RestController
@AllArgsConstructor
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog> implements OperationLogService, RemoteOperationLogService {

    private final RedisUtil redisUtil;

    @Override
    public int batchInsert(List<OperationLog> list) {
        return baseMapper.batchInsert(list);
    }

    /**
     * 插入操作日志
     */
    @Override
    public void insertOperationLog() {
        String requestLogId = LogUtil.getRequestLogId(redisUtil);
        if (StringUtils.isBlank(requestLogId)) {
            return;
        }
        Set<Object> set = redisUtil.sGet(LogRedisKeyUtil.logKey(Long.valueOf(requestLogId)));
        int size = null == set ? 0 : set.size();
        log.info("insertOperationLog | requestLogId : {}, operationLogs.size : {}", requestLogId, size);
        if (size == 0) {
            return;
        }
        List<OperationLog> operationLogs = StreamUtil.transListFT(set, e -> e instanceof OperationLog, e -> (OperationLog) e);
        this.batchInsert(operationLogs);
    }
}
